<?php
class BookmarksController extends AppController {

	var $name = 'Bookmarks';
	var $components = array('Site','RequestHandler');

	function index() {
		$this->checkSession();
		list($sort,$order)=$this->Site->getSort('modified');
 		$count=$this->Bookmark->findCount("Bookmark.user_id=".$this->luser['id']);
		$fields="User.login, User.name, Category.name, Category.description, Post.id, Post.title, Post.replies, Post.closed, Post.modified, Post.created,Post.points,Post.rated";
		$posts=$this->Bookmark->userBookmarks($this->luser['id'],$fields,$sort." ".$order,$this->pager($count,PAGESIZE));
		$this->set('bookmarks', $posts);
		$this->set('count', $count);
	}

	function add($pid = null) {
		$this->checkSession();
		$this->layout="ajax";

    if(!$pid) {
			exit;
		}

		$post=null;
		$post=$this->Bookmark->Post->findCount("Post.id=".$pid);
		if(!$post) {
      $this->render();
			exit;
		}
		$mc=$this->Bookmark->findCount("Bookmark.user_id=".$this->luser['id']." AND Bookmark.post_id=".$pid);
    if ($mc>0) { /*exists*/
			exit;
		}
		$this->Bookmark->create();
		$this->data['Bookmark']['user_id'] = $this->luser['id'];
		$this->data['Bookmark']['post_id'] = (int)$pid;
    if($this->Bookmark->save($this->data)) {
			$this->set("postid",$pid);
			if(!$this->RequestHandler->isAjax()) {
				$this->Session->setFlash('Bookmark created.');
				$this->redirect('/bookmarks/');
				exit;
			}
		}
		else { // error
			exit;
		}
	}

	function delete($pid = null) {
		$this->checkSession();
		$this->layout="ajax";

		if(!$pid) {
			exit;
		}

		if($this->Bookmark->delBookmark((int)$pid,$this->luser['id'])) {
			$this->set("postid",$pid);
 			if(!$this->RequestHandler->isAjax()) {
				$this->Session->setFlash('Bookmark deleted.');
				$this->redirect('/bookmarks/');
				exit;
			}
		}
	}

}
?>